package main

import (
	"context"
	"encoding/csv"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"github.com/chromedp/cdproto/dom"
	"github.com/chromedp/chromedp"
)

func main() {
	// 设置User-Agent并创建浏览器上下文
	opts := append(chromedp.DefaultExecAllocatorOptions[:],
		chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"),
	)
	ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancel()
	ctx, cancel = chromedp.NewContext(ctx)
	defer cancel()

	// 设置超时时间
	ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
	defer cancel()

	// 存储渲染后的HTML
	var htmlContent string

	// 执行浏览器操作
	err := chromedp.Run(ctx,
		chromedp.Navigate("https://www.lixiang.com/configuration.html?carModel=L6"),
		// 等待关键元素可见
		chromedp.WaitVisible(".configuration-wrap", chromedp.ByQuery),
		// 额外等待确保数据加载
		chromedp.Sleep(5*time.Second),
		// 模拟滚动
		chromedp.Evaluate(`window.scrollTo(0, document.body.scrollHeight);`, nil),
		chromedp.ActionFunc(func(ctx context.Context) error {
			node, err := dom.GetDocument().Do(ctx)
			if err != nil {
				return err
			}
			htmlContent, err = dom.GetOuterHTML().WithNodeID(node.NodeID).Do(ctx)
			if err != nil {
				return err
			}
			// 保存HTML用于调试
			os.WriteFile("rendered.html", []byte(htmlContent), 0644)
			return nil
		}),
	)
	if err != nil {
		log.Fatal("网页渲染失败:", err)
	}

	// 创建CSV文件
	file, err := os.Create("lixiang_L6_config.csv")
	if err != nil {
		log.Fatal("创建文件失败:", err)
	}
	defer file.Close()
	file.WriteString("\xEF\xBB\xBF") // UTF-8 BOM
	writer := csv.NewWriter(file)
	defer writer.Flush()
	writer.Write([]string{"配置类别", "配置项", "配置值"})

	// 解析HTML
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(htmlContent))
	if err != nil {
		log.Fatal("HTML解析失败:", err)
	}

	// 调试：检查是否找到.configuration-part
	if doc.Find(".configuration-part").Length() == 0 {
		log.Println("未找到.configuration-part元素，请检查选择器或HTML结构")
	}

	// 提取配置数据
	doc.Find(".configuration-part").Each(func(i int, section *goquery.Selection) {
		category := strings.TrimSpace(section.Find(".configuration-row.title .configuration-label").First().Text())
		log.Printf("找到类别: %s", category) // 调试

		section.Find(".configuration-row:not(.title)").Each(func(j int, row *goquery.Selection) {
			name := strings.TrimSpace(row.Find(".configuration-label").Text())
			values := row.Find(".configuration-value .text").Map(func(i int, s *goquery.Selection) string {
				return strings.TrimSpace(s.Text())
			})

			if name != "" && len(values) > 0 {
				// log.Printf("写入数据: %s, %s, %s", category, name, strings.Join(values, "/")) // 调试
				log.Printf("写入数据: %s, %s", name, strings.Join(values, "/")) // 调试
				writer.Write([]string{
					// category,
					name,
					strings.Join(values, "/"),
				})
			}
		})
	})

	fmt.Println("CSV文件生成成功：lixiang_L6_config.csv")
}
